#!/usr/bin/python
#encoding=utf-8

import sys,re,urllib2,urllib,cookielib,os
import cPickle as p

class Renren(object):
	'''for users of renren.

	get friendlist, download all the photos of the friend'''
	version='1.1'
	def __init__ (self):
		self.name=self.pwd=self.content=self.domain=self.origURL=''
		self.operate=''
		self.cj=cookielib.LWPCookieJar()
		if os.path.isfile('renren.coockie'):
			self.cj.revert('renren.coockie')
		self.opener=urllib2.build_opener( urllib2.HTTPCookieProcessor(self.cj))
		urllib2.install_opener(self.opener)

	def setinfo(self,username,password,domain,origURL):
		self.name=username
		self.pwd=password
		self.domain=domain
		self.origURL=origURL

	def login(self):
		'''login in the renren.com
		
		sucess return 0; fail return -1'''
		params={'email':self.name,'password':self.pwd}
		print ('login...')
		req=urllib2.Request("http://www.renren.com/PLogin.do",urllib.urlencode(params))
		self.operate=self.opener.open(req)
		if self.operate.geturl()==self.origURL:
			print ('ok!')
			self.cj.save('renren.coockie')
			return 0
		else:
			print ('fail!')
			return -1
	
	def getfriendid(self,name):
		'''get the id of the friend'''	
		if os.path.isfile('friendlist.dat'):
			friendlist= file('friendlist.dat','r')
			friends=p.load(friendlist)
			result={}
			for friend in friends:
				if name in friend['name']:
					print friend['id'], friend['name']
					result[friend['id']]=friend['name']
			return result
		else:
			print 'please getfriendlist() first'
			return None

	def getfriendlist(self):
		'''get the list of the friend'''
		global URL_FRIENDLIST
		URL_FRIENDLIST='http://friend.renren.com/myfriendlistx.do'
		result=self.opener.open(URL_FRIENDLIST)
		html=result.read()
		reg='friends=.*?];'
		f=re.search(reg,html)
		if f:
			x = f.group()
			x = x[8:-1]
			x = x.replace('true', 'True')
			x = x.replace('false', 'False')
			friends = eval(x)
			for friend1 in friends:
				for key in friend1.keys():
					if key=='name':
						friend1[key]=eval('u"' + friend1[key] + '"').encode('utf-8')			
			friendfile=file('friendlist.dat','w')
			p.dump(friends,friendfile)
			friendfile.close()


	def _dlphotos(self,urlreg,photos):
		'''down load photos for function _intoalbum()'''
		for _photo in photos:
			photo2html=self.opener.open(_photo).read()
			dladdr=urlreg.search(photo2html)
			if dladdr:
				dladdr=dladdr.group()
				dladdr=dladdr.replace('\/','/')
				dlcommand="wget -qN %s" %(dladdr)
				if os.system(dlcommand)==0:
					print "Downloading %s..." %(dladdr)	

	def _intoalbum(self,url):
		'''get into one album and download photos \
		for function getphotos()'''
		urlreg=re.compile('(?<=largeurl":").*?.jpg')
		namereg=re.compile('(?<=id = "albumname" value=").*?(?=" )')
		reg2=re.compile('http:\/\/photo.renren.com\/photo.*?t=')
		reg1=re.compile('http://photo.renren.com/.*m-.*?curpage=.')
		photohtml=self.opener.open(url).read()
		photopages=reg1.findall(photohtml)
		if photopages:
			photopages=list( set(photopages))
		else:
			photopages=[url,]
		num=0
		for _photopage in photopages:
			photohtml=self.opener.open(_photopage).read()
			if num==0:
				name=namereg.search(photohtml)
				if name:
					nextdir=DIR_NOW+os.sep+name.group()
				else:
					nextdir=DIR_NOW
				if not os.path.isdir(nextdir):
					os.mkdir(nextdir)
				os.chdir(nextdir)
			num=num+1
			photos=reg2.findall(photohtml)
			if photos:
				photos=list(set(photos))
				self._dlphotos(urlreg,photos)

	def getphotos(self,friendid):
		'''download photos of friend by friendid'''
		global DIR_TARGET
		global DIR_NOW
		global URL_PHOTO1
		global URL_PHOTO2
		URL_PHOTO1='http://photo.renren.com/photo/'
		URL_PHOTO2='/album/relatives'
		DIR_TARGET=os.getcwd()
		DIR_NOW=DIR_TARGET+os.sep+str(friendid)
		reg2=re.compile(URL_PHOTO1.replace('/','\/')+'.*m-.*?(?=\")')
		reg1=re.compile(URL_PHOTO1.replace('/','\/')+'.*'+URL_PHOTO2+'.*?(?=\")')
		if not os.path.isdir(str(friendid)):
			os.mkdir(DIR_NOW)
		url=URL_PHOTO1+str(friendid)+URL_PHOTO2
		albumhtml=self.opener.open(url).read()

		albumpages=reg1.findall(albumhtml)
		if albumpages:
			albumpages=list(set(albumpages))
		else:
			albumpages=[url,]
		for _albumpage in albumpages:
			albumhtml=self.opener.open(_albumpage).read()
			albums=reg2.findall(albumhtml)
			if albums:
				albums=list(set(albums))
				for _album in albums:
					self._intoalbum(_album)
			os.chdir(DIR_TARGET)

		




